/**
 * 成交数据审核
 * - 使用自定义封装组件，简化代码，统一管理。
 * - 2025-07-15 09:25:00 tzj
 * */

import BaseComponent from "../../components/BaseComponent";
import {mrhzApi} from "../../services/basic";
// import EditItem from "./EditItem";
import Dictionary from "../../services/dictionary";
import React, {useRef, useState} from "react";
import {DatePicker, Form, Input, message, Popconfirm, Radio} from "antd";
import "./style.css"
import moment from "moment";

// 显示的按钮
const buttons = ["query", "export"];
// 表格列信息
const columns = [...Dictionary.dealColumns];
const _userInfo = window.sessionStorage.getItem("userInfo")
if (_userInfo) {
  const userInfo = JSON.parse(_userInfo)
  const yybm = Number(userInfo.yybm)
  if (yybm >= 33060000000000047) {
    const index = columns.findIndex(item => item.dataIndex === 'lxfs')
    columns[index].render = (text) => {
      if (text.length <= 3) return text;
      return text.slice(0, 3) + '*'.repeat(text.length - 3);
    }
  }
}

columns.pop();

const RadioGroup = ({record, jzChange}) => {
  const [value, setValue] = useState(record.jz);
  const [shbz, setShbz] = useState("")
  const [cph, setCph] = useState(record.cph)
  const [cjh, setCjh] = useState(record.cjh)
  const [jssj, setJssj] = useState(record.jssj ? record.jssj.slice(0, 10) : "")
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false);
  const [required, setRequired] = useState(false);
  const formRef = useRef(null);

  console.log(33)
  console.log(jssj)
  // 临时信息，提交接口前
  const [valTemp, setTemp] = useState(record.jz)
  const onChange = (e) => {
    setLoading(true);
    const val = e.target.value
    setRequired(val === 1)
    setTemp(val)
    if (val === 2 || val === 1) {
      setOpen(true)
      setTimeout(() => {
        formRef.current.setFieldsValue({jssj: jssj ? moment(jssj, "YY-MM-DD") : null})
      })
    } else {
      jzChange(val, record).then(() => {
        setValue(val);
      }).finally(() => {
        setLoading(false);
      })
    }
  }

  const confirm = () => new Promise((resolve, reject) => {
    formRef.current.validateFields().then(() => {
      jzChange(valTemp, record, shbz, cph, cjh, jssj).then(() => {
        setOpen(false)
        resolve()
      }).finally(() => {
        setLoading(false);
        reject()
      })
    }).catch(() => {
      reject()
    })
  })


  const cancel = () => {
    setOpen(false)
    setLoading(false);
  }

  const dateChange = () => {
    const d = formRef.current.getFieldsValue().jssj
    const str = d ? moment(d).format("YYYY-MM-DD") : null
    console.log(str)
    setJssj(str)
  }

  const rules = [{required: true, message: "此为必填项"}];

  return (
    <Popconfirm
      icon={null}
      title={<>
        <Form ref={formRef}>
          <Form.Item label="原因" className='confirm-input'>
            <Input value={shbz} placeholder="请输入原因" onInput={(e) => setShbz(e.target.value)}/>
          </Form.Item>
          <Form.Item label="车牌号" className='confirm-input'>
            <Input value={cph} placeholder="请输入车牌号" onInput={(e) => setCph(e.target.value)}/>
          </Form.Item>
          <Form.Item label="车架号" className='confirm-input'>
            <Input value={cjh} placeholder="请输入车架号" onInput={(e) => setCjh(e.target.value)}/>
          </Form.Item>
          <Form.Item label='结算时间' name="jssj" required={required} rules={required?rules:[]}>
            <DatePicker value={jssj} className="date-jssj" onChange={dateChange} format={"YYYY-MM-DD"}
                        valueFormat={"YYYY-MM-DD"}/>
          </Form.Item>
        </Form>
      </>}
      onConfirm={confirm}
      onCancel={cancel}
      okText="确认"
      cancelText="取消"
      open={open}
    >
      <Radio.Group
        optionType="button"
        defaultValue={record.jz}
        value={value}
        size="small"
        disabled={loading}
        onChange={onChange}
        options={[
          {value: 0, label: '未核对'},
          {value: 1, label: '已核对'},
          {value: 2, label: '核对有误'},
        ]}
      />
    </Popconfirm>
  )
}

class pageCheckList extends BaseComponent {
  constructor(props) {
    super(props);
    // const that = this;
    const columns2 = [
      ...columns,
      {
        title: '审核状态',
        dataIndex: 'jz',
        // width: 240,
        align: "center",
        render: (text, record) => {
          return (<RadioGroup
            key={record.id + "" + record.jz} record={record}
            jzChange={this.jzChange}></RadioGroup>);
        },
        // 区别于页面展示dom，用于Excel导出时的值。
        excelRender: (text) => {
          return ["未核对", "已核对", "核对有误"][Number(text)];
        }
      }
    ]
    // 公司名称，来源账号，销售/客服，导购, 成交日期，进店日期，审核状态，
    // 要显示的form表单
    const formItemList = [
      "companies",
      {
        name: "accounts",
        label: "来源账号"
      },
      "serviceWx",
      {
        name: "person",
        label: "导购",
        keyword: "dg"
      },
      {
        name: "chooseDateRange",
        label: '到店/成交日期'
      },
      "followState",
      "check"
    ];

    this.state = {
      ...this.state,
      formItemList,
      buttons,
      // columns: columns2,
      filename: "成交数据审核",
      // tableTitle: true,
      params: {
        // ztbz: "1"
      },
    }
    this.defaultPageSize = 7;
    this.columns = columns2;
    this.queryApi = mrhzApi.selectPagecj;
    // this.deleteApi = lzApi.delete;
    // this.EditItem = EditItem;
  }

  // 审核状态切换
  jzChange = (value, record, shbz, cph, cjh, jssj) => {

    return new Promise((resolve, reject) => {
      console.log(value, cph, cjh, jssj)

      if (value === 1 && !cph && !cjh) {
        message.warning("请输入车牌号或者车架号");
        reject()
        return
      }
      mrhzApi.putSwjz({
        lzid: record.id,
        swjz: value,
        shbz, cph, cjh, jssj
      }).then((res) => {
        if (res.code === "1") {
          this.queryDataList();
          resolve();
        } else {
          message.warning(res.msg || "未知异常！");
          reject();
        }
      }).catch((res) => {
        message.warning(res.msg || "未知异常！");
        reject()
      });
    })
  }

  beforeQuery = () => {
    // console.log(111)
    // console.log(this.form.dataForm)
    // const dataForm = this.form.dataForm;
    // dataForm.cjqsrq = dataForm.cjqsrq && dataForm.cjqsrq.length === 10 ? dataForm.cjqsrq + ' 00:00:00' : dataForm.cjqsrq;
    // dataForm.ddqsrq = dataForm.ddqsrq && dataForm.ddqsrq.length === 10 ? dataForm.ddqsrq + ' 00:00:00' : dataForm.ddqsrq;
    // dataForm.cjzzrq = dataForm.cjzzrq && dataForm.cjzzrq.length === 10 ? dataForm.cjzzrq + ' 23:59:59' : dataForm.cjzzrq;
    // dataForm.ddzzrq = dataForm.ddzzrq && dataForm.ddzzrq.length === 10 ? dataForm.ddzzrq + ' 23:59:59' : dataForm.ddzzrq;
    // console.log(this.form.dataForm)
  }
}

export default pageCheckList;